package com.spring.springboot.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @author liucong
 * 图片和base64码互转方法
 */
public class Base64Util {
    /**
     * 图片转化成base64字符串
     *
     * @param imgPath
     * @return
     */
    public static String getImageStr(String imgPath) {
        // 待处理的图片
        String imgFile = imgPath;
        InputStream in = null;
        byte[] data;
        // 返回Base64编码过的字节数组字符串
        String encode = null;
        // 对字节数组Base64编码
//        BASE64Encoder encoder = new BASE64Encoder();

        Base64.Encoder encoder = Base64.getEncoder();

        try {
            // 读取图片字节数组
            File f = new File(imgFile);
            in = new FileInputStream(f);
            data = new byte[in.available()];
            in.read(data);
            encode = encoder.encodeToString(data).replaceAll("\r|\n", "");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return encode;
    }

    /**
     * 通过url获取图片并转换为Base64字节码
     *
     * @param httpPath
     * @return
     */
    public static String getImageStrFromHttp(String httpPath) {
        InputStream inStream = null;
        byte[] data;
        // 返回Base64编码过的字节数组字符串
        String encode = null;
        // 对字节数组Base64编码
        Base64.Encoder encoder = Base64.getEncoder();
        httpPath = httpPath.replaceAll("https://eajwy.cn", "http://172.16.99.44:18080");
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(httpPath).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inStream = connection.getInputStream();
                data = readInputStream(inStream);
                encode = encoder.encodeToString(data).replaceAll("\r|\n", "");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return encode;
    }

    /**
     * 通过输入流获取图片数据
     *
     * @param inStream
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[1024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len = 0;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }

    /**
     * base64字符串转化成图片
     *
     * @param imgData     图片编码
     * @param imgFilePath 存放到本地路径
     * @return
     * @throws IOException
     */
    @SuppressWarnings("finally")
    public static boolean generateImage(String imgData, String imgFilePath) throws IOException {
        // 图像数据为空
        if (imgData == null) {
            return false;
        }
//        BASE64Decoder decoder = new BASE64Decoder();
        Base64.Decoder decoder = Base64.getDecoder();
        OutputStream out = null;
        try {
            out = new FileOutputStream(imgFilePath);
            // Base64解码
            byte[] b = decoder.decode(imgData);
            for (int i = 0; i < b.length; ++i) {
                // 调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out.write(b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
            return true;
        }
    }

    public static void main(String[] args) throws IOException {

//        String code = getImageStrFromHttp("https://eajwy.cn/picture/HX/20200602/1591100463065/1591100463065.jpg");
//        generateImage(code,"d:/test/1.jpg");
//        String httpPath = "https://eajwy.cn/picture/HX/20200602/1591102346826/1591102346826.jpg";
//        httpPath.replaceAll("eajwy.cn", "172.16.99.44:18080");
//        System.out.println("====================================" + httpPath);
    }
}
